package com.kungfuhacking.wristbandpro.location.presenter;

import android.util.Log;
import android.view.View;

import com.alibaba.fastjson.JSONObject;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.kungfuhacking.wristbandpro.base.bean.RequestBean;
import com.kungfuhacking.wristbandpro.base.presenter.BasePresenter;
import com.kungfuhacking.wristbandpro.location.bean.HistoryLocationBean;
import com.kungfuhacking.wristbandpro.location.bean.HistoryResBean;
import com.kungfuhacking.wristbandpro.location.view.IHistoryView;
import com.kungfuhacking.wristbandpro.login.activity.LoginActivity;
import com.kungfuhacking.wristbandpro.net.BaseNoTObserver;
import com.kungfuhacking.wristbandpro.net.RetrofitHttpUtil;
import com.kungfuhacking.wristbandpro.utils.Constant;
import com.kungfuhacking.wristbandpro.utils.LogUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import io.reactivex.disposables.Disposable;


/**
 * 历史轨迹
 * Created by Aaron on 17/5/9.
 */

public class IHistoryPresenter extends LocationPresenter implements BasePresenter {

    private IHistoryView iHistoryView;
    private String TAG = getClass().getSimpleName();

    public IHistoryPresenter(IHistoryView iHistoryView) {
        this.iHistoryView = iHistoryView;
    }

    /**
     * 设置老人弹出框的信息好背景
     */
    @Override
    public View getInfoWindow(Marker marker) {
        return iHistoryView.getMarkerView(marker);
    }

    /**
     * 设置老人弹出框的信息好背景
     */
    @Override
    public View getInfoContents(Marker marker) {
        return iHistoryView.getMarkerView(marker);
    }


    /**
     * 获取历史轨迹
     *
     * @param starTime 开始的时间段
     * @param endTime  结束的时间段
     */
    public void getHistoryRecord(long starTime, long endTime) {

        JSONObject j = new JSONObject();
        j.put("token", iHistoryView.getToken());
        j.put("id", iHistoryView.getSp().getString(Constant.CURRENTOLDID, ""));
        j.put("startTime", starTime);
        j.put("endTime", endTime);

        LogUtil.d("tag", "startTime:" + new Date(starTime) + ",endTime:" + new Date(endTime));

        RetrofitHttpUtil.getInstance().getLocList(new BaseNoTObserver<HistoryResBean>() {
            @Override
            public void onHandleSuccess(HistoryResBean historyResBean) {
                iHistoryView.hideLoading();
                handResult(historyResBean);
            }

            @Override
            public void onHandleError(String message) {
                iHistoryView.hideLoading();
                iHistoryView.showErr(message);
            }

            @Override
            public void onReLogin(String message) {
                iHistoryView.showErr(message);
                iHistoryView.hideLoading();
                iHistoryView.nextActivityWithSingleTask(LoginActivity.class);
            }

            @Override
            public void onSubscribe(Disposable d) {
                compositeDisposable.add(d);
                iHistoryView.showLoading("加载中...");
            }
        }, new RequestBean().setData(j.toString()));

    }

    private void handResult(HistoryResBean historyResBean) {
        List<HistoryLocationBean> locationList = historyResBean.getLocationList();

        if (locationList == null || locationList.size() == 0) {
            iHistoryView.showErr("未查询到该时间段的定位信息");
            if (aMap != null)
                aMap.clear();
            return;
        }
        //创建历史定位图标
        createLocationMarks(locationList);
    }

    private void createLocationMarks(List<HistoryLocationBean> locationList) {

        if (aMap != null)
            aMap.clear();

        LogUtil.d(TAG, "有" + locationList.size() + "条轨迹记录");

//        //根据服务器返回的点的集合个数,创建多少个点
//        for (int i = 0; i < locationList.size(); i++) {
//            //创建点
//            LatLng location = new LatLng(locationList.get(i).getLatitude(), locationList.get(i).getLongitude());
//            addMarker(location, locationList.get(i));
////            options.add(location);//添加画线的点
//            aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(location, 18));//移动到location位置,并设置缩放比例
//        }

        selectPoint(locationList);
    }

    private void selectPoint(List<HistoryLocationBean> locationList) {

        List<HistoryLocationBean> copyList = new ArrayList<>();
        copyList.add(locationList.get(0));

        loopPoint(locationList, copyList);
    }

    private void loopPoint(List<HistoryLocationBean> locationList, List<HistoryLocationBean> copyList) {
        LatLng l1;
        long t1;
        LatLng l2;
        long t2;
        //根据服务器返回的点的集合个数,创建多少个点
        for (int i = 0; i < locationList.size(); i++) {

            l1 = new LatLng(locationList.get(i).getLatitude(), locationList.get(i).getLongitude());
            //更新时间
            t1 = locationList.get(i).getUpdateTime();

            boolean isAdd = true;//是否添加到集合中
            for (int j = 0; j < copyList.size(); j++) {

                l2 = new LatLng(copyList.get(j).getLatitude(), copyList.get(j).getLongitude());
                //更新时间
                t2 = copyList.get(j).getUpdateTime();
                //比较两个点之间的距离
                float distanceMeters = AMapUtils.calculateLineDistance(l1, l2);

                if (distanceMeters > 20) //距离大于20m, 或者定位间隔时间大于3分钟
                    continue;

                if (Math.abs((t2 - t1)) > 5 * 60 * 1000)
                    continue;

                isAdd = false;
                break;

            }

            if (isAdd)
                copyList.add(locationList.get(i));
        }

        Log.d(TAG, "筛选后的定位点的个数: " + copyList.size());
        //创建定位点
        for (int i = 0; i < copyList.size(); i++) {
            createPonit(copyList.get(i));
//            Log.d(TAG, "定位信息:" + copyList.get(i).getAddressDescription() + ",时间:" + new Date(copyList.get(i).getUpdateTime()).toLocaleString());
        }

    }

    /**
     * 创建定位点
     *
     * @param historyLocationBean
     */
    private void createPonit(HistoryLocationBean historyLocationBean) {

//        Log.d(TAG, "定位的点:" + historyLocationBean.getUpdateTime() + ",:" + historyLocationBean.getAddressDescription());
        //创建点
        LatLng location = new LatLng(historyLocationBean.getLatitude(), historyLocationBean.getLongitude());
        addMarker(location, historyLocationBean);
//            options.add(location);//添加画线的点
        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(location, 18));//移动到location位置,并设置缩放比例
    }

    private void addMarker(LatLng latlng, HistoryLocationBean locationList) {

        MarkerOptions options = new MarkerOptions();
        options.icon(iHistoryView.getBitmap());
        options.anchor(0.5f, 0.5f);
        options.position(latlng);
        mLocMarker = aMap.addMarker(options);
        mLocMarker.setObject(locationList);
        mLocMarker.setTitle("title");
    }

    @Override
    public void clearRequest() {
        compositeDisposable.clear();
    }
}
